import { syncRef, useRouteQuery } from '@peng_kai/kit/libs/vueuse';
import dayjs from 'dayjs';

/** 预设的数据转换器 */
const presetTransforms = {
  // 时间范围
  rangeTime(v: any) {
    const rangeValue = Array.isArray(v) && v.length === 2
      ? v.map(i => Number(i)).filter(i => i > 10 ** 12).sort().map(ts => dayjs(ts))
      : [];

    return (rangeValue.length ? rangeValue : []) as [dayjs.Dayjs, dayjs.Dayjs];
  },
};

type PresetTransformNames = keyof typeof presetTransforms;
type AnyFn = (v: any) => any;

export function useSyncUrlSearchParams<D extends Record<string, any>>(
  data: D,
  transforms?: { [K in keyof D]?: ((v: any) => D[K]) | PresetTransformNames },
) {
  const route = useRoute();
  const router = useRouter();

  for (const key of Object.keys(data)) {
    const name = transforms?.[key];
    const transform = (presetTransforms[name as PresetTransformNames] ?? name) as AnyFn;
    const param = useRouteQuery(key, data[key], { route, router, transform });

    syncRef(param, toRef(data, key), { direction: 'both' });
  }
}
